ABC270 C - Simple path
https://atcoder.jp/contests/abc270/tasks/abc270_c
提出
code: python
from collections import defaultdict
from collections import deque
n, x, y = list(map(int, input().split()))
uv = list(map(int, input().split())) for _ in range(n-1)
print(uv)
graph = defaultdict(list)
for i in uv:
graph[i0].append(i1)
graph[i1].append(i0)
print(graph)
que = deque()
que.append(x)
visited = {2}
path = set()
ans = []
while que:
d = que.popleft()
for i in graphd:
if not i in visited:
que.append(i)
visited.add(i)
print(ans)
解答
code: python
import sys
from collections import defaultdict
sys.setrecursionlimit(10 ** 7)
n, x, y = map(int, input().split())
uv = list(map(int, input().split())) for _ in range(n-1)
d = defaultdict(list)
for u, v in uv:
du.append(v)
dv.append(u)
# # print(d)
# defaultdict(<class 'list'>, {1: 2, 3, 2: 1, 3: 1, 4, 5, 4: 3, 5: 3})
ans = x
def dfs(now, prev):
if now == y:
print(*ans)
exit()
# print(dnow)
# 1
# 2, 3
# 1, 4, 5
# 3 continue の行き先は... -> ans.pop()
for next in dnow:
if next == prev:
continue
ans.append(next)
# print(ans)
# 2, 1
# 2, 1, 3
# 2, 1, 3, 4
# 2, 1, 3, 5
# print(next, now)
# 1 2
# 3 1
# 4 3
# 5 3
dfs(next, now)
# print(ans) 2, 1, 3, 4
ans.pop()
dfs(x, 0)
テーマ
#graph #dfs
メモ
トヨタ自動車プログラミングコンテスト2022(AtCoder Beginner Contest 270))A~C問題Python解説
提出
code: python
from collections import defaultdict
from collections import deque
n, x, y = map(int, input().split())
uv = list(map(int, input().split())) for _ in range(n-1)
d = defaultdict(list)
for u, v in uv:
du.append(v)
dv.append(u)
q = deque()
visited = set()
path = []
q.append(x)
while len(q):
next = q.popleft()
if next in visited:
continue
else:
visited.add(next)
path.append(next)
if y in dnext:
path.append(y)
break
for p in dnext:
q.append(p)
print(" ".join(map(str, path)))